package org.sunrise.game.game.server;

import io.netty.channel.ChannelHandlerContext;
import org.sunrise.game.common.log.LogCore;
import org.sunrise.game.common.network.client.BaseClientHandler;
import org.sunrise.game.common.network.client.BaseClientManager;
import org.sunrise.game.common.network.message.MessageType;
import org.sunrise.game.common.network.message.SocketMessage;
import org.sunrise.game.common.utils.Utils;

import java.nio.charset.StandardCharsets;

public class GameToExternalHandler extends BaseClientHandler {
    private final int gameId;
    private boolean isAuthMessage = true;
    public GameToExternalHandler(int gameId, String nodeId) {
        super(nodeId);
        this.gameId = gameId;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String connectMessage = Utils.GAME_CONNECT + gameId;
        ctx.writeAndFlush(new SocketMessage(MessageType.biz, connectMessage.getBytes(StandardCharsets.UTF_8)));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SocketMessage socketMessage) {
        byte[] data = socketMessage.getData();
        if (isAuthMessage) {
            String responseMessage = new String(data, StandardCharsets.UTF_8);
            if (responseMessage.startsWith(Utils.GAME_CONNECT_RESPONSE + Utils.SUCCESS)) {
                String serverNodeId = responseMessage.substring(Utils.GAME_CONNECT_RESPONSE.length() + Utils.SUCCESS.length());
                BaseClientManager.getBaseClient(getNodeId()).setServerNodeId(serverNodeId);
                LogCore.Client.info("connected to server success, cur NodeId = { {} }, serverNodeId = { {} } remoteAddress = { {} }", getNodeId(), serverNodeId, ctx.channel().remoteAddress());

            } else {
                LogCore.Client.error("connected to server failed, cur NodeId = { {} }", getNodeId());
            }
            isAuthMessage = false;
        } else {
            BaseClientManager.recvFromServer(getNodeId(), data);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        int externalIdByNodeId = GameManager.getConnectToExternalIdByNodeId(getNodeId());
        LogCore.ServerStartUp.error("external server disconnected, curNodeId = {}, externalId = {}, remoteAddress = {}", getNodeId(), externalIdByNodeId, ctx.channel().remoteAddress());
        GameManager.getGameClient().externalOffline(externalIdByNodeId);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LogCore.GameServer.error("Exception caught: {}", cause.getMessage());
        ctx.close();
    }
}
